import html2canvas from "html2canvas";

export const guid = (prefix = "", surfix = "") => {
	const tmp = "xxxyxxx-yxxx-";
	let res = tmp.concat(+new Date()).replace(/[xy]/g, (c) => {
		const r = (Math.random() * 16) | 0;
		const v = c === "x" ? r : (r & 0x3) | 0x8;
		return v.toString(16);
	});
	return `${prefix ? prefix + "-" : ""}${res}${surfix ? "-" + surfix : ""}`;
};

export const query2string = (query) => {
	const queryString = Object.keys(query)
		.map((key) => key + "=" + encodeURIComponent(query[key]))
		.join("&");
	return queryString;
};

export const buildFormData = (formData, data, parentKey) => {
	if (
		data &&
		typeof data === "object" &&
		!(data instanceof Date) &&
		!(data instanceof File) &&
		!(data instanceof Blob)
	) {
		Object.keys(data).forEach((key) => {
			buildFormData(
				formData,
				data[key],
				parentKey ? `${parentKey}[${key}]` : key
			);
		});
	} else {
		const value = data == null ? "" : data;
		if (parentKey) formData.append(parentKey, value);
	}
};

export const jsonToForm = (data) => {
	const formData = new FormData();
	buildFormData(formData, data);
	return formData;
};

export const jsonToXXX = (data) => {
	let params = "";
	Object.keys(data).map((key) => {
		params += `${key}=${data[key]}&`;
	});
	params = params.substring(0, params.length - 1);
	return params;
};
export const convertBase64UrlToBlob = (urlData, type = "") => {
	var arr = urlData.split(","),
		mime = arr[0].match(/:(.*?);/)[1] || type,
		bstr = atob(arr[1]),
		n = bstr.length,
		u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	return new Blob([u8arr], { type: mime });
};

export const html2Img = ({
	html,
	quality = 1,
	scale,
	type = "base64", // base64 blob file
}) => {
	return new Promise((resolve, reject) => {
		if (!html) {
			console.log("none-html", html);
			reject();
		}
		try {
			html2canvas(html, { allowTaint: true, useCORS: true, scale })
				.then((canvas) => {
					console.log("canvas", canvas);
					canvas.setAttribute("crossOrigin", "anonymous");
					const base64 = canvas.toDataURL("image/png", quality);
					console.log("base64", base64.length);
					const blob = convertBase64UrlToBlob(base64);
					console.log("blob", blob);
					const file = new File([blob], `jiachuang-${+new Date()}.png`);
					console.log("file", file.size);
					const result = {
						base64,
						blob,
						file,
					};
					resolve(result[type] || result);

					// if (type == "base64") resolve(base64);
					// else {
					// 	canvas.toBlob((blob) => {
					// 		console.log("blob", blob);
					// 		if (type == "blob") resolve(blob);
					// 		else if (type == "file") {
					// 			const file = new File([blob], `jiachuang-${+new Date()}.png`);

					// 			console.log("file", file);
					// 			resolve(file);
					// 		}
					// 	});
					// }
				})
				.catch((e) => {
					console.log("html2canvas", e);
					reject(e);
				});
		} catch (e) {
			console.error(e);
			reject(e);
		}
	});
};

